package com.harmony.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class AppClient {

    public void run() {
        // 定义线程池，NioEventLoopGroup
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 启动一个客户端需要的辅助类，bootstrap
        Bootstrap bootstrap = new Bootstrap();

        try {
            bootstrap.group(group)
                    .remoteAddress(new InetSocketAddress(8090))
                    // 选择客户端的Channel实现
                    .channel(NioSocketChannel.class)
                    // 初始化一个什么样子的channel
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                        }
                    });

            // 尝试连接服务器
            ChannelFuture future = bootstrap.connect().sync();
            // 获取 channel, 进行数据传输
            future.channel().writeAndFlush(Unpooled.copiedBuffer("Hello".getBytes(StandardCharsets.UTF_8)));
            // 阻塞程序，等到接受消息
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new AppClient().run();
    }

}
